//index.js
//获取应用实例
import util from '../../utils/util'
import {
  GetMenu,
  getNoticeArticle,
  getIndexSliderList,
  getChatList,
  EventShow,
  ServiceList,
  getMarketList,
  chatSpeakGood,
  GetVollegeInfo,
  delChatRecord,
  delMarketRecord,
  PlacedTop,
  CancelTop,
  MenuArticle
} from '../../config/api'

const app = getApp()

Page({
  data: {
    villageInfo: [], //地址信息
    quick_menu: [],
    navList: [], //导航测试数据
    tabs: ['村聊', '事件动态', '志愿服务', '集市广场', '务工招聘'],
    tabActive: 0,
    TzList:[],
    noticeList: [], //通知列表
    sliderList: [], //广告位图片链接
    limit: 20, //每页显示20条
    chartList: [], //村聊列表
    evenList: [], //事件列表
    volList: [], //志愿列表服务列表
    marketList: [], //集市的列表
    workList: [], //务工招聘列表
    vollagePage: 1, //村聊分页
    evenPage: 1, //世间动态分页
    volPage: 1, //志愿服务分页
    marketPage: 1, //集市分页
    workPage: 1, //务工招聘分页
    isTopping: false
  },

  onLoad: function() {
    let adminInfo = wx.getStorageSync('adminInfo');
    if (!!adminInfo) {
      this.setData({
        isTopping: true
      })
    }
    this.getFuncMenu(); // 快捷菜单
    this.getNavList(); //获取相应的导航菜单
    this.getTZList();
    this.getNoticeList(); //获得通知列表
    this.getGuangGaoList(); //获取宣传广告位链接
    this.getChartList(); //村聊列表
    this.getVolleageAddress();
  },

  resetAllPage() {
    let that = this;
    that.setData({
      vollagePage: 1, //村聊分页
      chartList: [],
      evenPage: 1, //世间动态分页
      volList: [],
      volPage: 1, //志愿服务分页
      marketPage: 1, //集市分页
      marketList: [],
      workPage: 1, //务工招聘分页
      workList: [],
      evenList: [],
    });
  }, //重置所有的分页


  //获取村聊列表
  getChartList() {
    let that = this;
    let member = wx.getStorageSync('member');
    let params = {
      vollege_id: '',
      page: that.data.vollagePage,
      limit: that.data.limit,
      belong_vollege_id: app.globalData.vollege_id,
      belong_town_id: app.globalData.town_id,
    };
    if (member) {
      params = {
        vollege_id: member.vollege_id,
        idcard: member.idcard,
        page: that.data.vollagePage,
        limit: that.data.limit,
        belong_vollege_id: app.globalData.vollege_id,
        belong_town_id: app.globalData.town_id,
      };
    }
    util.apiRequest(getChatList, params, null).then(r => {
      console.log('村聊列表：', r);
      that.setData({
        chartList: [...that.data.chartList, ...r.data.data]
      });
      if (r.data.data.length == 0 && that.data.vollagePage != 1) {
        wx.showToast({
          title: '',
          icon: 'loading',
          duration: 1000
        })
      }

    });
  },

  onTop(e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    let chat_list = that.data.chartList;
    console.log("置顶：", item)
    if (item.place_top != 1) {
      util.apiRequest(PlacedTop,{id:item.id}).then(r =>{
        console.log("置顶结果：",r)
        if (r.data.code) {
          item.place_top = 1;
          chat_list.splice(index, 1)
          chat_list.splice(0, 0, item)
          that.setData({
            chartList: chat_list
          })
          console.log("置顶后：", that.data.chartList)
        }
      })
    }else{
      util.apiRequest(CancelTop, { id: item.id }).then(r => {
        console.log("取消置顶结果：", r)
        if (r.data.code) {
          that.setData({
            vollagePage:1,
            chartList:[]
          })
          that.getChartList()
        }
      })
    }
  },

    //拨打电话
    dial(e) {
      let that = this;
      console.log('e', e.currentTarget.dataset.phone);
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.phone //仅为示例，并非真实的电话号码
      })
    },

  //获取事件动态的列表
  getEvenList() {
    let that = this;
    let params = {
      vollege_id: app.globalData.vollege_id,
      page: that.data.evenPage,
      limit: that.data.limit
    };
    util.apiRequest(EventShow, params, null).then(r => {
      that.setData({
        evenList: [...that.data.evenList, ...r.data.data]
      });
      if (that.data.evenPage != 1 && r.data.data.length == 0) {
        wx.showToast({
          title: '没有更多了',
          icon: 'loading',
          duration: 1000
        })
      }
    });
  }, //获取事件动态的列表


  getVolList() {
    let that = this;
    let params = {
      vollege_id: app.globalData.vollege_id,
      page: that.data.volPage,
      limit: that.data.limit
    };
    util.apiRequest(ServiceList, params, null).then(r => {
      console.log('志愿服务列表为：', r.data.data.data);
      that.setData({
        volList: [...that.data.volList, ...r.data.data.data]
      });
      if (that.data.volPage != 1 && r.data.data.data.length == 0) {
        wx.showToast({
          title: '没有更多了',
          icon: 'loading',
          duration: 1000
        })
      }
    });
  }, //获取志愿服务列表


  getMarketList() {
    let that = this;
    let member = wx.getStorageSync('member');
    let params = {
      page: that.data.marketPage,
      limit: that.data.limit,
      vollege_id: app.globalData.vollege_id
    };
    if (member) {
      params = {
        page: that.data.marketPage,
        limit: that.data.limit,
        vollege_id: app.globalData.vollege_id,
        idcard: member.idcard,
      };
    }
    util.apiRequest(getMarketList, params, null).then(r => {
      console.log('获取到的集市列表为：', r);
      that.setData({
        marketList: [...that.data.marketList, ...r.data.data]
      });
      if (that.data.marketPage != 1 && r.data.data.length == 0) {
        wx.showToast({
          title: '没有更多了',
          icon: 'loading',
          duration: 1000
        })
      };
    });
  }, //获取集市列表


  getWorkList() {
    let that = this;
    let params = {
      page: that.data.workPage,
      limit: that.data.limit
    };
    wx.request({
      url: 'https://zhaopintong.yuehuio.com/api/External/job_list', //仅为示例，并非真实的接口地址
      data: params,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log('务工招聘请求的接口为：', res.data.data);
        that.setData({
          workList: [...that.data.workList, ...res.data.data]
        });
        if (that.data.workPage != 1 && res.data.data.length == 0) {
          wx.showToast({
            title: '没有更多了',
            icon: 'loading',
            duration: 1000
          })
        };

      }
    })
  }, //获取务工招聘的列表

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that = this;
    console.log('触发页面触底的事件!');
    let index = that.data.tabActive;
    switch (index) {
      case 0:
        console.log('村聊的逻辑');
        that.setData({
          vollagePage: that.data.vollagePage + 1
        })
        that.getChartList();
        break;
      case 1:
        console.log('事件动态的逻辑');
        that.setData({
          evenPage: that.data.evenPage + 1
        })
        that.getEvenList();
        break;
      case 2:
        console.log('志愿服务的逻辑');
        that.setData({
          volPage: that.data.volPage + 1
        });
        that.getVolList();
        break;
      case 3:
        console.log('集市的逻辑');
        that.setData({
          marketPage: that.data.marketPage + 1
        });
        that.getMarketList();
        break;
      case 4:
        console.log('务工招聘');
        that.setData({
          workPage: that.data.workPage + 1
        });
        that.getWorkList();
        break;
    }
  },


  tabChange(e) {
    let that = this;
    console.log('e.currentTarget.dataset.index', e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index;
    that.setData({
      tabActive: e.currentTarget.dataset.index
    });
    that.resetAllPage();
    switch (index) {
      case 0:
        console.log('村聊的逻辑');
        that.getChartList();
        break;
      case 1:
        console.log('事件动态的逻辑');
        that.getEvenList();
        break;
      case 2:
        console.log('志愿服务的逻辑');
        that.getVolList();
        break;
      case 3:
        console.log('集市的逻辑');
        that.getMarketList();
        break;
      case 4:
        console.log('务工招聘');
        that.getWorkList();
        break;
    }
  },

  //删除村聊记录
  delChatRecord(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    let arr = that.data.chartList;
    wx.showModal({
      title: '提示',
      content: '您确认删除该记录吗？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          util.apiRequest(delChatRecord, {
            id: item.id
          }, null).then(r => {
            wx.showToast({
              title: r.data.info,
            })
            console.log('删除村聊之前：', arr);
            arr.splice(index, 1);
            console.log('删除村聊之后：', arr);
            that.setData({
              chartList: arr
            })
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //删除集市记录
  delMarketRecord(e) {
    let that = this;
    console.log('删除集市记录：！');
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    let arr = that.data.marketList;
    wx.showModal({
      title: '提示',
      content: '您确认删除该记录吗？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          util.apiRequest(delMarketRecord, {
            id: item.id
          }, null).then(r => {
            console.log('删除结果为：', r.data.info);
            wx.showToast({
              title: r.data.info,
              icon: 'loading',
              duration: 2000
            })
            console.log('删除村聊之前：', arr);
            arr.splice(index, 1);
            console.log('删除村聊之后：', arr);
            that.setData({
              marketList: arr
            })
          });
        } else if (res.cancel) {

        }
      }
    })


  },

  //获取村地址
  getVolleageAddress() {
    let that = this;
    let params = {
      vollege_id: app.globalData.vollege_id
    };
    util.apiRequest(GetVollegeInfo, params, null).then(r => {
      console.log('村信息：', r.data.data);
      that.setData({
        villageInfo: r.data.data.reverse()
      });
    });

  }, //获取村相应的地址

  getTZList() {
    let that = this;
    util.apiRequest(MenuArticle, {
      vollege_id: app.globalData.vollege_id,
      category:'village_notice'
    }, null).then(r => {
      console.log('通知列表', r)
      that.setData({
        TzList: r.data.data.slice(0, 6)
      })
    })
  }, 

  getNoticeList() {
    let that = this;
    util.apiRequest(getNoticeArticle, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('新闻列表', r)
      that.setData({
        noticeList: r.data.data.slice(0, 6)
      })
    })
  }, //获得新闻列表

  toNewsDetail(e) {
    let that = this;
    console.log('前往消息通知列表');
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/newsDetail/newsDetail?id=' + id,
    })
  }, //跳转前往消息列表详情

  getFuncMenu() { // 获取功能菜单
    let that = this;
    let params = {
      vollege_id: app.globalData.vollege_id,
      belongs: 'index_top_tool'
    }
    util.apiRequest(GetMenu, params, null).then(r => {
      console.log('快捷菜单：', r)
      that.setData({
        quick_menu: r.data.data
      })
    })
  },

  getNavList() {
    let that = this;
    let params = {
      vollege_id: app.globalData.vollege_id,
      belongs: 'index_main_menu'
    };
    util.apiRequest(GetMenu, params, null).then(r => {
      console.log('获得菜单的数据为：', r.data.data);
      that.setData({
        navList: r.data.data.slice(0, 8)
      });
    });
  }, //获取导航列表

  ToNavDetail(e) {
    let that = this;
    console.log('e:', e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    if (item.url == "/pages/village/village") {
      wx.navigateTo({
        url: item.url + "?pid=" + item.id + "&" + item.param
      });
      return;
    }
    delete item.param;
    wx.navigateTo({
      url: item.url + "?item=" + JSON.stringify(item)
    });
  }, //跳转到相应的导航详情

  getGuangGaoList() {
    let that = this;
    let params = {
      type: 4,
      grid_id: app.globalData.vollege_id,
    };
    util.apiRequest(getIndexSliderList, params, null).then(r => {
      console.log('广告宣传片为：', r.data.data);
      that.setData({
        sliderList: r.data.data
      })
    });
  }, //获取首页广告宣传图片


  toOutLink(e) {
    let that = this;
    console.log('e跳转链接', e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    if (item.link == null || item.link == '') {
      console.log('链接地址为空！');
      return;
    }

    if (item.link.indexOf('http') == -1 && item.link.indexOf('https') == -1) {
      let startStep = item.link.indexOf('=')
      console.log('123:', startStep)
      let appId = item.link.substring(startStep)
      console.log('appId:', appId)
      wx.navigateToMiniProgram({
        appId: appId,
        path: '',
        envVersion: 'release', // 打开正式版
        success(res) {
          // 打开成功
        },
        fail: function (err) {
          console.log(err);
        }
      })
    }

    if (item.link.indexOf("http") != -1) {
      window.location.href = item.link;
    } else {
      wx.navigateTo({
        url:item.link
      })
    }
  }, //跳转到相应的链接


  previewImg(e) {
    let that = this;
    console.log('e.currentTarget', e.currentTarget);
    wx.previewImage({
      current: e.currentTarget.dataset.img,
      urls: e.currentTarget.dataset.imgs
    });
  }, //预览图片

  chatSpeakGood(e) {
    let that = this;
    console.log('村聊点赞item！', e.currentTarget.dataset.item);
    console.log('村聊点赞index！', e.currentTarget.dataset.index);
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    let member = wx.getStorageSync('member')
    if (!member) {
      that.showDialogTitle(app.globalData.info);
      return;
    }
    let params = {
      idcard: member.idcard,
      talk_id: e.currentTarget.dataset.item.id,
      user_name: member.name,
      phone: member.mobile,
      address: '',
    };
    console.log('点赞提交的参数为params:', params);
    let objList = that.data.chartList;
    util.apiRequest(chatSpeakGood, params).then(r => {
      console.log('点赞结果：', r.data);
      if (item.thumb_sta == 0) {
        objList[index].thumb_sta = 1;
        objList[index].thumbs_up += 1;
        objList[index].thumbs_up_list = [...objList[index].thumbs_up_list, ...[{
          user_name: member.name,
          idcard: member.idcard
        }]];
      } else {
        objList[index].thumb_sta = 0;
        objList[index].thumbs_up -= 1;
        objList[index].thumbs_up_list.pop();
      }
      console.log('bojList', objList);
      that.setData({
        chartList: objList
      });
    });

  }, //村聊点赞


  showDialogTitle(title) {
    wx.showModal({
      title: '提示',
      content: title,
      showCancel: false,
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          return;
        }
      }
    })
  },

  //跳转前往村聊详情
  toChatDetail(e) {
    let that = this;
    console.log('跳转前往村聊详情！', e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pages/new_index/chat_detail/chat_detail?id=' + item.id
    });
  }, //跳转前往村聊详情

  //跳转前往志愿服务详情
  toVolDetail(e) {
    let that = this;
    console.log('跳转前往志愿服务详情：', e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    if (item.status == 1 || item.status == 4) {
      wx.navigateTo({
        url: '/pages/culture/unsolved/unsolved?id=' + item.id,
      })
    } else {
      wx.navigateTo({
        url: '/pages/culture/resolved/resolved?id=' + item.id,
      })
    }
  },
  //跳转前往志愿服务详情

  // 跳转前往集市详情
  toMarketDetail(e) {
    let that = this;
    console.log('跳转前往集市详情：', e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pages/new_index/market_detail/market_detail?id=' + item.id
    });
  },
  // 跳转前往集市详情

  //跳转前往务工招聘
  toWorkDetail(e) {
    let that = this;
    console.log('跳转前往务工招聘！', e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pages/new_index/job_list/job_detail/job_detail?id=' + item.id
    });
  },

  onShareAppMessage: function (res) {
    console.log(res)
    if (res.from === 'button') { }
    return {
      title: '',
      path: '/pages/index/index',
      success: function (res) {
        console.log('成功', res)
      }
    }
  }

})